<template>
  <InfiniteList :load-function="loadChatData" data-field="alerts" pagination-field="pagination">
    <!-- 列表内容插槽 -->
    <template #default="{ data }">
      <q-list separator>
        <q-item v-for="chat in data" :key="chat.id" clickable v-ripple class="chat-item"
          :class="chat.read_date == 0 ? 'unread-item' : ''" @click="openChat(chat)">
          <q-item-section avatar>
            <q-avatar size="48px">
              <img v-if="chat.User && chat.User.avatar_urls.h" :src="chat.User.avatar_urls.h" :alt="chat.title" />
              <q-icon v-else name="person" size="48px" color="primary" />
            </q-avatar>
          </q-item-section>

          <q-item-section>
            <q-item-label class="chat-title">{{ chat.title }}</q-item-label>
            <q-item-label caption class="chat-message">
              {{ chat.alert_text }}
            </q-item-label>
          </q-item-section>

          <q-item-section side top>
            <q-item-label caption class="chat-time">
              {{ formatTime(chat.event_date) }}
            </q-item-label>
            <q-badge rounded color="primary" v-if="chat.read_date == 0" />
          </q-item-section>
        </q-item>
      </q-list>
    </template>

    <!-- 自定义空状态 -->
    <template #empty>
      <q-icon name="chat" size="64px" color="grey-5" />
      <div class="text-grey-6 q-mt-md">暂无聊天记录</div>
    </template>
  </InfiniteList>

  <router-view />
</template>

<script setup>
import { getAlerts } from '../utils/api'
import { useRouter } from 'vue-router'
import InfiniteList from '../components/InfiniteList.vue'
import { formatTime, unreadColor, unreadColorDark } from 'src/utils/common'

const router = useRouter()

// 数据加载函数
const loadChatData = async (page) => {
  const result = await getAlerts(page)
  return result
}

// 打开聊天
const openChat = (chat) => {
  router.push(`/chat/${chat.conversation_id}`)
}
</script>

<style scoped lang="scss">
.chat-item {
  padding: 12px 16px;
  min-height: 72px;
  align-items: center;
}

.chat-item:hover {
  background-color: #f5f5f5;
}

.chat-title {
  font-weight: 500;
  font-size: 16px;
  margin-bottom: 4px;
}

.chat-message {
  font-size: 14px;
  //color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.chat-time {
  font-size: 12px;
  //color: #999;
  margin-bottom: 8px;
}

/* 深色主题适配 */
.body--dark .chat-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.unread-item {
  background-color: v-bind(unreadColor);
}

.body--dark .unread-item {
  background-color: v-bind(unreadColorDark);
}
</style>